package home

import (
	"adai.design/jarvis/common/db"
	"adai.design/jarvis/member"
	"encoding/json"
	"github.com/globalsign/mgo/bson"
	"time"
)

const (
	CharLoggerDBCollection = "home-char-log"
)

type characteristicMarkCell struct {
	Home           string      `json:"home" bson:"home"`
	Accessory      string      `json:"aid" bson:"aid"`
	Service        int         `json:"sid" bson:"sid"`
	Characteristic int         `json:"cid" bson:"cid"`
	Value          interface{} `json:"value" bson:"value"`
	Time           time.Time   `json:"-" bson:"time"`
	Date           string      `json:"time" bson:"-"`
}

// 属性记录插入
func insertCharacteristicLog(info *characteristicMarkCell) error {
	session, err := db.GetSession()
	if err != nil {
		return err
	}
	defer session.Close()

	collection := session.DB("home").C(CharLoggerDBCollection)
	err = collection.Insert(info)
	if err != nil {
		return err
	}
	return nil
}

type characteristicQueryInfo struct {
	AId    string `json:"aid"`
	SId    int    `json:"sid"`
	CId    int    `json:"cid"`
	Limit  int    `json:"limit,omitempty"`
	Before string `json:"before,omitempty"`
	After  string `json:"after,omitempty"`
}

//h *Home, pkg *member.MessagePkg
func handleMemberCharacteristicLog(h *Home, pkg *member.MessagePkg) error {
	var info characteristicQueryInfo
	err := json.Unmarshal(pkg.Msg.Data, &info)
	if err != nil {
		return err
	}
	session, err := db.GetSession()
	if err != nil {
		return err
	}
	defer session.Close()
	collection := session.DB("home").C(CharLoggerDBCollection)

	var list []*characteristicMarkCell

	if info.Before != "" && info.After != "" {
		before, _ := time.ParseInLocation("2006-01-02 15:04:05", info.Before, time.Local)
		after, _ := time.ParseInLocation("2006-01-02 15:04:05", info.After, time.Local)
		err = collection.Find(
			bson.M{"aid": info.AId, "sid": info.SId, "cid": info.CId,
				"time": bson.M{"$gte": after, "$lte": before}}).All(&list)
	} else {
		err = collection.Find(
			bson.M{"aid": info.AId, "sid": info.SId, "cid": info.CId}).Sort("-time").Limit(info.Limit).All(&list)
	}

	var logs []interface{}
	for _, l := range list {
		cell := map[string]interface{}{}
		cell["time"] = l.Time.In(time.Local).Format("2006-01-02 15:04:05")
		cell["value"] = l.Value
		logs = append(logs, cell)
	}

	data := &map[string]interface{}{
		"aid":    info.AId,
		"sid":    info.SId,
		"cid":    info.CId,
		"before": info.Before,
		"after":  info.After,
		"limit":  info.Limit,
		"logs":   logs,
	}
	dataBuf, _ := json.Marshal(data)

	ack := &member.MessagePkg{
		Type: pkg.Type,
		Ctx:  pkg.Ctx,
		Msg: &member.Message{
			Path:   pathCharacteristicLog,
			Method: member.MsgMethodGet,
			Home:   h.instance.Id,
			State:  "ok",
			Data:   dataBuf,
		},
	}
	return h.replyMemberResult(ack)
}
